using System;
using System.Collections.Generic;
using System.Collections;
using Com.ContentRendering.Api.DataEngine.Exceptions;

namespace Com.ContentRendering.Api.DataEngine.Handler.Self
{
    /// <summary/>
    internal class EnumeratorSelfHandler : AbstractSelfHandler
    {
        /// <summary/>
        internal EnumeratorSelfHandler(
            ReflectionCache reflectionCache,
            object value)
            : base(
            reflectionCache,
            value) { }

        /// <summary/>
        internal override IEnumerator<object> Parse()
        {
            // if the object doesn't implement the enumerator interface then move on
            if (!typeof(IEnumerator).IsInstanceOfType(this._value))
            {
                return base._successor.Parse();
            }

            // rather than just returning the enumerator, copy its values to a new list ... although this
            // seems like a waste of resources, it is a good idea since the lifetime of the enumerator is not known

            IEnumerator enumerator = (IEnumerator)this._value;

            List<object> parsedValues = new List<object>();

            try
            {
                // always reset the state of the enumerator ... cause we have no idea what it is
                enumerator.Reset();
            }
            catch (NotImplementedException exception)
            {
                throw new ResetNotImplementedException(exception);
            }

            // move each value into the new list
            while (enumerator.MoveNext())
            {
                parsedValues.Add(enumerator.Current);
            }

            return parsedValues.GetEnumerator();    
        }
    }
}
